package com.cpr.core.concurrency.waitAndNotify;

import lombok.SneakyThrows;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Chen Panrui
 * created at 2022/4/16 17:04
 */
public class PartyTest {

    private static final String IN = "in";
    private static final String OUT = "out";
    private static final String INTERRUPTION = "interrupt";
    /**
     * 可以被中断的线程
     */
    private static final Map<String, MyThread> INTERRUPT_ABLE = new ConcurrentHashMap<>(8);

    public static void main(String[] args) {
        Party happyParty = new Party();

        Scanner scanner = new Scanner(System.in);
        System.out.println("测试方式:\n" +
                "输入(xx_in)或者(xx_out)表示某个人进入或者退出party\n" +
                //"输入(xx_interrupt)表示某个wait进入party的人中断\n" +
                "输入info查看目前party人数");
        while (scanner.hasNext()){
            String info = scanner.next();
            if("exit".equals(info)){
                break;
            }
            if(StringUtils.isEmpty(info)){
                System.err.println("不合法的数据:" + info);
                continue;
            }
            if("info".equals(info)){
                happyParty.info();
                continue;
            }

            String[] print = info.split("_");

            if(IN.equals(print[1])){
                MyThread thread = new MyThread(new Control(print[1], happyParty));
                thread.setName(print[0]);
                thread.start();
                INTERRUPT_ABLE.put(print[0], thread);
            } else if(OUT.equals(print[1])){
                MyThread thread = new MyThread(new Control(print[1], happyParty));
                thread.setName(print[0]);
                thread.start();
                INTERRUPT_ABLE.remove(print[0]);
            } else if(INTERRUPTION.equals(print[1])){
                /*
                 *
                 */
                MyThread t = INTERRUPT_ABLE.get(print[0]);
                t.interrupt();
            } else {
                System.err.println("不合法的参数:" + print[1]);
            }
        }
    }

    static class MyThread extends Thread{
        private Control control;

        public void setControl(Control c){
            this.control = c;
        }

        public MyThread(Control c){
            this.control = c;
        }

        @SneakyThrows
        @Override
        public void run() {
            control.inOrOut();
        }
    }

}
